#common
export projectRoot=$(CURDIR)
export buildOut=${projectRoot}/.build/out
wordCt=$(words ${MAKECMDGOALS})
module=$(word 1,${MAKECMDGOALS})
moduleCmd=$(word 2,${MAKECMDGOALS})

T=docker
#设定homer,环境变量或者make入参
ifeq (${HOMER},)
export HOMER=$(HOME)
endif
export GOPATH=${HOMER}/.gopath

ifeq (${GOPROXY},)
export GOPROXY=goproxy.io
endif

export repoPrefix=lb.hubx.dev:5000/hubx
export tag=latest

#宏定义 start

define go_run_direct
go build -ldflags '-w -s' -o ${outTarget} $(1)
endef

define go_run_docker
docker run --rm -i --name golang_builder -v ${projectRoot}:${projectRoot} \
  -w ${projectRoot} \
  -e "https_proxy=${hp}" \
  -v ${GOPATH}:${GOPATH} \
  -e "GOPATH=${GOPATH}" \
  -e "GOPROXY=${GOPROXY}" \
  --entrypoint=/bin/sh \
  golang:alpine \
  -c "go build -ldflags '-w -s' -o ${outTarget} $(1)"
endef

define goBuild = 
$(call go_run_$(T),$(1))
endef

#宏定义 end

#有子命令
ifneq (${moduleCmd},)

export imageName=${repoPrefix}/${module}:${tag}

binName=${module}
outTarget=${projectRoot}/.build/out/${binName}
moduleDir=$(shell dirname $$(find ${projectRoot}/ -name Makefile.mk | grep "/${module}/Makefile.mk"))
mkfile=${moduleDir}/Makefile.mk

${module} : ${GOPATH}/bin/go-bindata \
	${GOPATH}/bin/go-bindata-assetfs \
	${GOPATH}/bin/protoc-gen-gogofast \
	${buildOut}
	@echo "use ${module} module gopath:${GOPATH}"

include ${mkfile}

${GOPATH}/bin/go-bindata:
	go install github.com/jteeuwen/go-bindata/go-bindata

${GOPATH}/bin/go-bindata-assetfs:
	go install github.com/elazarl/go-bindata-assetfs/go-bindata-assetfs

${GOPATH}/bin/protoc-gen-gogofast:
	go install github.com/gogo/protobuf/protoc-gen-gogofast

${buildOut}: 
	mkdir -p ${buildOut}

buildx: #在alpine容器中构建
	$(call goBuild,${moduleDir}/cmd/main.go)
	ls -lh ${outTarget}

imagex: #基于构建二进制，构建镜像
	docker build -f ${moduleDir}/Dockerfile -t ${imageName} ${buildOut}

pushx: #
	docker push ${imageName}

testx: #测试镜像
	docker run --rm -it  --net host ${imageName}

cleanx: #清空构建
	rm -f  ${outTarget}　&& docker rmi -f ${imageName}

endif

#无参数
ifeq ($(wordCt),0)
mods:
	@find ${projectRoot} -name Makefile.mk | while read line; \
	do \
	  echo $$(basename $$(dirname $$line)); \
	  grep '#-' $$line | awk -F'#-' {'print $$2'}; \
	  grep '^[^#[:space:]].*: ' $${line} | grep -v ".PHONY" | awk -F'#'  {'print "--> "$$1  "#"$$2'}; \
	  echo "\n"; \
	done 
	@echo "exec help ${GOPATH}"
endif


#只有模块参数
ifeq ($(wordCt),1)

${module}:
	@find ${projectRoot} -name Makefile.mk | grep "/${module}/Makefile.mk" | xargs grep '^[^#[:space:]].*: ' | awk -F'#'  {'print "--> "$$1  "#"$$2'}
	@grep '^[^#[:space:]].*: #' ./Makefile | awk -F'#'  {'print "--> "$$1  "#"$$2'}

cleanall:
	find ${buildOut} -type f | xargs rm -f

endif